<template>
  <div id="container"></div>
</template>

<script setup>
import {ref, onMounted, toRaw} from 'vue';
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'


let cube;
const container = ref(null);
const scene = ref(null);
const camera = ref(null);
const renderer = ref(null);
const orbit = ref(null);

onMounted(() => {
  init()
  animate()
})

function init() {
  container.value = document.getElementById('container')
  initScene()
  initCamera()
  initRenderer()
  initOrbit()
  initGrid()
  initBox()
}

// 创建场景
function initScene () {
  scene.value = new THREE.Scene();
  // scene.value.background = new THREE.Color('#999')
}
// 创建相机
function initCamera() {
  camera.value = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
  camera.value.position.set(0 , 4 , 10);
  camera.value.lookAt(0, 0, 0);
}
// 创建渲染器
function initRenderer() {
  renderer.value = new THREE.WebGLRenderer({
    antialias: true,// 设置抗锯齿
  });
  renderer.value.setSize(window.innerWidth, window.innerHeight);
  container.value.appendChild(renderer.value.domElement);

  // renderer.value.render(scene.value, camera.value)
}

// 创建 轨道控制器
function initOrbit() {
  orbit.value = new OrbitControls(camera.value, renderer.value.domElement);
}

function initGrid() {
  const gridHelper = new THREE.GridHelper(10, 10);
  scene.value.add(gridHelper)
}

// 创建盒子
function initBox() {
  cube = new THREE.Mesh(
      new THREE.BoxGeometry(1, 1, 1),
      new THREE.MeshBasicMaterial()
  )
  const cube2 = new THREE.Mesh(
      new THREE.BoxGeometry(1, 1, 1),
      new THREE.MeshBasicMaterial({
        color: new THREE.Color('#ff0000')
      })
  )
  cube2.position.set(-2 ,0 ,0)
  scene.value.add(cube)
  scene.value.add(cube2)
}

let angle = 0
// 动画
function animate() {
  requestAnimationFrame(animate);
  orbit.value.update();
  // 渲染场景和相机
  renderer.value.render(toRaw(scene.value), camera.value);
}

</script>

<style>
#container {
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>
